'use strict';

var app = angular.module('caffe', ['ngResource', 'ngRoute']);

app.config(function($routeProvider) {
    $routeProvider
        .when('/', {templateUrl: 'view/welcome.html', controller: 'EventListCtrl'})
		.when('/admin', {templateUrl: 'view/admin.html'})
		.when('/konobar', {templateUrl: 'view/konobar.html'})
        .when('/zaposleni', {templateUrl: 'view/zaposleni.html', controller: 'ZaposleniListCtrl'})
        .when('/artikli', {templateUrl: 'view/artikal.html', controller: 'ArtikalListCtrl'})
        .when('/porudzbine', {templateUrl: 'view/porudzbina.html', controller: 'PorudzbinaListCtrl'})
        .when('/distributeri', {templateUrl: 'view/distributer.html', controller: 'DistributerListCtrl'})
        .when('/kategorije', {templateUrl: 'view/kategorija.html', controller: 'KategorijaListCtrl'})
        .when('/stolovi', {templateUrl: 'view/sto.html', controller: 'StoListCtrl'})
        .when('/nerazduzeno', {templateUrl: 'view/nerazduzeno.html', controller: 'NerazduzenoListCtrl'})
        .when('/nenapravljena', {templateUrl: 'view/nenapravljena.html', controller: 'NenapravljenaListCtrl'})
        .when('/login', {templateUrl: 'view/login.html', controller: 'LoginCtrl'})
		.when('/podaci', {templateUrl: 'view/podaciZaposlenog.html', controller: 'PodaciCtrl'})
        // AngularJS does not allow template-less controllers, so we are specifying a
        // template that we know we won't use. Here is more info on this
        // https://github.com/angular/angular.js/issues/1838
        .when('/logout', {templateUrl: 'login.html', controller: 'LogoutCtrl'})
        .otherwise({redirectTo: '/'});
});

/*
 app.config(function($httpProvider) {
 $httpProvider.interceptors.push(function($rootScope, $location, $q) {
 return {
 'request': function(request) {
 // if we're not logged-in to the AngularJS app, redirect to login page
 $rootScope.loggedIn = $rootScope.loggedIn || $rootScope.username;
 if (!$rootScope.loggedIn && $location.path() != '/login') {
 $location.path('/login');
 }
 return request;
 },
 'responseError': function(rejection) {
 // if we're not logged-in to the web service, redirect to login page
 if (rejection.status === 401 && $location.path() != '/login') {
 $rootScope.loggedIn = false;
 $location.path('/login');
 }
 return $q.reject(rejection);
 }
 };
 });
 });
 */
app.factory('EventService', function($resource) {
    return $resource('/api/events/:id');
});

app.factory('KonobarService', function($resource) {
    return $resource('/zavrsni/rest/konobar/:id');
});

app.factory('ArtikalService', function($resource) {
    return $resource('/zavrsni/rest/artikal/:id');
});

app.factory('PorudzbinaService', function($resource) {
    return $resource('/zavrsni/rest/porudzbina/:id');
});

app.factory('StavkaService', function($resource) {
    return $resource('/zavrsni/rest/stavka/:id');
});

app.factory('RazduzenjeService', function($resource) {
    return $resource('/zavrsni/rest/razduzenje/:id');
});

app.factory('DistributerService', function($resource) {
    return $resource('/zavrsni/rest/distributer/:id');
});

app.factory('KategorijaService', function($resource) {
    return $resource('/zavrsni/rest/kategorija/:id');
});

app.factory('StoService', function($resource) {
    return $resource('/zavrsni/rest/sto/:id');
});

app.factory('NerazduzenoService', function($resource) {
    return $resource('/zavrsni/rest/porudzbina/razduzeno/0');
});

app.factory('NenapravljenaService', function($resource) {
    return $resource('/zavrsni/rest/porudzbina/napravljena/0');
});

app.factory('SessionService', function($resource) {
    return $resource('/zavrsni/rest/konobar/');
});


app.controller('LoginCtrl', function($scope, $rootScope, $location, SessionService) {
    $scope.konobar = {
		korisnickoIme: '', 
		korisnickaSifra: ''
	};

    $scope.login = function() {
        $scope.konobar = SessionService.save($scope.konobar, function(success) {
            $rootScope.loggedIn = true;
            $location.path('/');
        }, function(error) {
            $scope.loginError = true;
        });
    };
});

app.controller('LogoutCtrl', function($rootScope, $location, SessionService) {
    (new SessionService()).$delete(function(success) {
        $rootScope.loggedIn = false;
        $location.path('/login');
    });
});


app.controller('EventListCtrl', function($scope, $location, EventService) {

    EventService.query(function(events){
        $scope.events = events;
    });

    $scope.editEvent = function(event) {
        $scope.opts = ['on', 'off'];

        if (event === 'new') {
            $scope.newEvent = true;
            $scope.event = {name: '', shortname: '', phonenumber: '', state: '', voteoptions: [{id:1, name: ''}]};
        }
        else {
            $scope.newEvent = false;
            $scope.event = event;
        }
    };

    /*$scope.save = function() {
     if (!$scope.event._id) {
     var newEvent = new EventService($scope.event);
     newEvent.$save(function(){
     $scope.events.push(newEvent);
     });
     }
     else {
     $scope.events.forEach(function(e) {
     if (e._id === $scope.event._id) {
     e.$save();
     }
     });
     }
     };*/

    $scope.delete = function() {
        $scope.events.forEach(function(e, index) {
            if (e._id == $scope.event._id) {
                $scope.event.$delete({id: $scope.event._id, rev: $scope.event._rev}, function() {
                    $scope.events.splice(index, 1);
                });
            }
        });
    };

    $scope.addVoteOption = function() {
        $scope.event.voteoptions.push({id: $scope.event.voteoptions.length+1, name: null});
    };

    $scope.removeVoteOption = function(vo) {
        $scope.event.voteoptions.splice(vo.id-1, 1);
        // need to make sure id values run from 1..x (web service constraint)
        $scope.event.voteoptions.forEach(function(vo, index) {
            vo.id = index+1;
        });
    };
});


app.controller('ZaposleniListCtrl',function($scope, $location, KonobarService) {

    KonobarService.query(function(konobari){
        $scope.konobari = konobari;
    });
	
	KonobarService.query(function(konobari){
        $scope.konobari = konobari;
    });

    $scope.izmeniKonobara = function (konobar) {
        if(konobar === 'novi'){
            $scope.noviKonobar = true;
            $scope.konobar = {
                ime: "",
                prezime: "",
                godinaRodjenja: "",
                mestoRodjenja: "",
                korisnickoIme: "",
                korisnickaSifra: ""
            };
        }
        else {
            $scope.noviKonobar = false;
            $scope.konobar = konobar;
        }
    }

    $scope.save = function(konobar) {
         if (!$scope.konobar.konobarID) {
             var noviKonobar = new KonobarService($scope.konobar);
             if (noviKonobar.ime === ""
                 || noviKonobar.prezime===""
                 || noviKonobar.godinaRodjenja===""
                 || noviKonobar.mestoRodjenja===""
                 || noviKonobar.korisnickoIme===""
                 || noviKonobar.korisnickaSifra===""){
                    window.alert("Niste popunili sva polja.");
             }else{
                 noviKonobar.$save(function(){
                     $scope.konobari.push(noviKonobar);
                 });
             }

         } else {
             $scope.konobari.forEach(function(e) {
                 if (e.konobarID === $scope.konobar.konobarID) {
                     e.$save({id: e.konobarID});
                 }
             });
         }
     };

     $scope.delete = function(konobar) {
         $scope.konobari.forEach(function(e, index) {
             if (e.konobarID == $scope.konobar.konobarID) {
                 $scope.konobar.$delete({id: $scope.konobar.konobarID}, function() {
                     $scope.konobari.splice(index, 1);
                 });
             }
         });
     };

    $scope.order = 'ime';

});



app.controller('ArtikalListCtrl',function($scope, $location, ArtikalService, KategorijaService, DistributerService) {

    ArtikalService.query(function(artikli){
        $scope.artikli = artikli;
    });

    KategorijaService.query(function(kategorije){
        $scope.kategorije = kategorije;
    });

    DistributerService.query(function(distributeri){
        $scope.distributeri = distributeri;
    });

    $scope.izmeniArtikal = function (artikal) {
        if(artikal === 'novi'){
            $scope.noviArtikal = true;
            $scope.artikal = {
                nazivArtikla: "",
                ambalaza: "",
                rokTrajanja: "",
                stanjeNaZalihama: "",
                cena: "",
                distributerID: "",
                kategorijaID: ""
            };
        }
        else {
            $scope.noviArtikal = false;
            $scope.artikal = artikal;
        }
    }


    $scope.save = function() {
        if (!$scope.artikal.artikalID) {
            var noviArtikal = new ArtikalService($scope.artikal);
            if (noviArtikal.nazivArtikla === ""
                || noviArtikal.ambalaza===""
                || noviArtikal.rokTrajanja===""
                || noviArtikal.stanjeNaZalihama===""
                || noviArtikal.cena===""
                || noviArtikal.distributerID===""
                || noviArtikal.kategorijaID===""){
                window.alert("Niste popunili sva polja.");
            }else{
                noviArtikal.$save(function(){
                    $scope.artikli.push(noviArtikal);
                });
            }
        }
        else {
            $scope.artikli.forEach(function(e) {
                if (e.artikalID === $scope.artikal.artikalID) {
                    e.$save({id: e.artikalID});
                }
            });
        }
    };

    $scope.delete = function(artikal) {
        $scope.artikli.forEach(function(e, index) {
            if (e.artikalID === $scope.artikal.artikalID) {
                $scope.artikal.$delete({id: $scope.artikal.artikalID}, function() {
                    $scope.artikli.splice(index, 1);
                });
            }
        });
    };

    $scope.order = 'nazivArtikla';
});

app.controller('PorudzbinaListCtrl',function($scope, $location, PorudzbinaService, KonobarService, StoService, StavkaService, RazduzenjeService) {

    PorudzbinaService.query(function(porudzbine){
        $scope.porudzbine = porudzbine;
    });
	
	StavkaService.query(function(stavke){
		$scope.stavke = stavke;
	});
	
	RazduzenjeService.query(function(razduzenja){
		$scope.razduzenja = razduzenja;
	});
	
	/*PorudzbinaService.query({id: 1000}, function(porudzbine){
		$scope.porudzbine = porudzbine;
	});*/
	
	//http://stackoverflow.com/questions/14523679/can-you-pass-parameters-to-an-angularjs-controller-on-creation

    KonobarService.query(function(konobari){
        $scope.konobari = konobari;
    });

    StoService.query(function(stolovi){
        $scope.stolovi = stolovi;
    });

    $scope.izmeniPorudzbinu = function (porudzbina) {

        var n = new Date();
        var yyyy = n.getFullYear();
        if (n.getMonth()+1 < 10){
            var m = n.getMonth()+1;
            var mm = "0"+m;
        }else { var mm = n.getMonth()+1}
        var dd = n.getDate();
        var datum = yyyy+'-'+mm+'-'+dd;

        if(porudzbina === 'novi'){
            $scope.novaPorudzbina = true;
            $scope.porudzbina = {
                datumPorudzbine: datum,
                razduzeno: "",
                konobarID: "",
                stoID: "",
                razduzenjeID: ""
            };
        }
        else {
			$scope.novaPorudzbina = false;
            $scope.porudzbina = porudzbina;
        }
    }


     $scope.save = function() {
        if (!$scope.porudzbina.porudzbinaID) {
            var novaPorudzbina = new PorudzbinaService($scope.porudzbina);
            novaPorudzbina.$save(function(){
                $scope.porudzbine.push(novaPorudzbina);
            });
        } else {
            $scope.porudzbine.forEach(function(e) {
                if (e.porudzbinaID === $scope.porudzbina.porudzbinaID) {
                    e.$save({id: e.porudzbinaID});
                }
            });
        }
    };

    $scope.order = 'datumPorudzbine';


    $scope.delete = function(porudzbina) {
        $scope.porudzbine.forEach(function(e, index) {
            if (e.porudzbinaID == $scope.porudzbina.porudzbinaID) {
                $scope.porudzbina.$delete({id: $scope.porudzbina.porudzbinaID}, function() {
                    $scope.porudzbine.splice(index, 1);
                });
            }
        });
    };

});

app.controller('DistributerListCtrl',function($scope, $location, DistributerService) {

    DistributerService.query(function(distributeri){
        $scope.distributeri = distributeri;

    });

    $scope.izmeniDistributera = function (distributer) {

        if(distributer === 'novi'){
            $scope.noviDistributer = true;
            $scope.distributer = {
                nazivDistributera: ""
            };
        }
        else {
            $scope.noviDistributer = false;
            $scope.distributer = distributer;
        }
    }

    $scope.save = function() {
        if (!$scope.distributer.distributerID) {
            var noviDistributer = new DistributerService($scope.distributer);
            if (noviDistributer.nazivDistributera === ""){
                window.alert("Niste popunili polje za naziv distributera.");
            }else{
                noviDistributer.$save(function(){
                    $scope.distributeri.push(noviDistributer);
                });
            }
        } else {
            $scope.distributeri.forEach(function(e) {
                if (e.distributerID === $scope.distributer.distributerID) {
                    e.$save({id: e.distributerID});
                }
            });
        }
    };

    $scope.order = 'nazivDistributera';


    $scope.delete = function(distributer) {
        $scope.distributeri.forEach(function(e, index) {
            if (e.distributerID == $scope.distributer.distributerID) {
                $scope.distributer.$delete({id: $scope.distributer.distributerID}, function() {
                    $scope.distributeri.splice(index, 1);
                });
            }
        });
    };

});

app.controller('KategorijaListCtrl',function($scope, $location, KategorijaService) {

    KategorijaService.query(function(kategorije){
        $scope.kategorije = kategorije;

    });

    $scope.izmeniKategoriju = function (kategorija) {

        if(kategorija === 'novi'){
            $scope.novaKategorija = true;
            $scope.kategorija = {
                nazivKategorije: ""
            };
        }
        else {
            $scope.novaKategorija = false;
            $scope.kategorija = kategorija;
        }
    }

    $scope.save = function() {
        if (!$scope.kategorija.kategorijaID) {
            var novaKategorija = new KategorijaService($scope.kategorija);
            if (novaKategorija.nazivKategorije === ""){
                window.alert("Niste popunili polje za naziv kategorije.");
            }else{
                novaKategorija.$save(function(){
                    $scope.kategorije.push(novaKategorija);
                });
            }
        } else {
            $scope.kategorije.forEach(function(e) {
                if (e.kategorijaID === $scope.kategorija.kategorijaID) {
                    e.$save({id: e.kategorijaID});
                }
            });
        }
    };

    $scope.delete = function(kategorija) {
        $scope.kategorije.forEach(function(e, index) {
            if (e.kategorijaID == $scope.kategorija.kategorijaID) {
                $scope.kategorija.$delete({id: $scope.kategorija.kategorijaID}, function() {
                    $scope.kategorije.splice(index, 1);
                });
            }
        });
    };

    $scope.order = 'nazivKategorije';

});

app.controller('StoListCtrl',function($scope, $location, StoService) {

    StoService.query(function(stolovi){
        $scope.stolovi = stolovi;

    });

    $scope.izmeniSto = function (sto) {

        if(sto === 'novi'){
            $scope.noviSto = true;
            $scope.sto = {
                brojStola: ""
            };
        }
        else {
            $scope.noviSto = false;
            $scope.sto = sto;
        }
    }

    $scope.save = function() {
        if (!$scope.sto.stoID) {
            var noviSto = new StoService($scope.sto);
            if (noviSto.brojStola === ""){
                window.alert("Niste popunili polje za redni broj stola.");
            }else{
                noviSto.$save(function(){
                    $scope.stolovi.push(noviSto);
                });
            }
        } else {
            $scope.stolovi.forEach(function(e) {
                if (e.stoID === $scope.sto.stoID) {
                    e.$save({id: e.stoID});
                }
            });
        }
    };

    $scope.delete = function(sto) {
        $scope.stolovi.forEach(function(e, index) {
            if (e.stoID == $scope.sto.stoID) {
                $scope.sto.$delete({id: $scope.sto.stoID}, function() {
                    $scope.stolovi.splice(index, 1);
                });
            }
        });
    };


});

app.controller('NerazduzenoListCtrl',function($scope, $location, NerazduzenoService, KonobarService, StoService) {

    NerazduzenoService.query(function(porudzbine){
        $scope.porudzbine = porudzbine;
    });

    KonobarService.query(function(konobari){
        $scope.konobari = konobari;
    });

    StoService.query(function(stolovi){
        $scope.stolovi = stolovi;
    });

    $scope.izmeniPorudzbinu = function (porudzbina) {

        var n = new Date();
        var yyyy = n.getFullYear();
        if (n.getMonth()+1 < 10){
            var m = n.getMonth()+1;
            var mm = "0"+m;
        }else { var mm = n.getMonth()+1}
        var dd = n.getDate();
        var datum = yyyy+'-'+mm+'-'+dd;

        if(porudzbina === 'novi'){
            $scope.novaPorudzbina = true;
            $scope.porudzbina = {
                datumPorudzbine: datum,
                razduzeno: "",
                konobarID: "",
                stoID: "",
                razduzenjeID: ""
            };
        }
        else {
            $scope.novaPorudzbina = false;
            $scope.porudzbina = porudzbina;
        }
    }


    $scope.save = function() {
        if (!$scope.porudzbina._id) {
            var novaPorudzbina = new PorudzbinaService($scope.porudzbina);
            novaPorudzbina.$save(function(){
                $scope.porudzbine.push(novaPorudzbina);
            });
        } else {
            $scope.porudzbine.forEach(function(e) {
                if (e._id === $scope.porudzbina._id) {
                    e.$save();
                }
            });
        }
    };

    $scope.order = 'datumPorudzbine';


    $scope.delete = function(porudzbina) {
        $scope.porudzbine.forEach(function(e, index) {
            if (e.porudzbinaID == $scope.porudzbina.porudzbinaID) {
                $scope.porudzbina.$delete({id: $scope.porudzbina.porudzbinaID}, function() {
                    $scope.porudzbine.splice(index, 1);
                });
            }
        });
    };

});


app.controller('NenapravljenaListCtrl',function($scope, $location, NenapravljenaService, KonobarService, StoService) {

    NenapravljenaService.query(function(porudzbine){
        $scope.porudzbine = porudzbine;
    });

    KonobarService.query(function(konobari){
        $scope.konobari = konobari;
    });

    StoService.query(function(stolovi){
        $scope.stolovi = stolovi;
    });

    $scope.izmeniPorudzbinu = function (porudzbina) {

        var n = new Date();
        var yyyy = n.getFullYear();
        if (n.getMonth()+1 < 10){
            var m = n.getMonth()+1;
            var mm = "0"+m;
        }else { var mm = n.getMonth()+1}
        var dd = n.getDate();
        var datum = yyyy+'-'+mm+'-'+dd;

        if(porudzbina === 'novi'){
            $scope.novaPorudzbina = true;
            $scope.porudzbina = {
                datumPorudzbine: datum,
                razduzeno: "",
                konobarID: "",
                stoID: "",
                razduzenjeID: ""
            };
        }
        else {
            $scope.novaPorudzbina = false;
            $scope.porudzbina = porudzbina;
        }
    }


    $scope.save = function() {
        if (!$scope.porudzbina._id) {
            var novaPorudzbina = new PorudzbinaService($scope.porudzbina);
            novaPorudzbina.$save(function(){
                $scope.porudzbine.push(novaPorudzbina);
            });
        } else {
            $scope.porudzbine.forEach(function(e) {
                if (e._id === $scope.porudzbina._id) {
                    e.$save();
                }
            });
        }
    };

    $scope.order = 'datumPorudzbine';


    $scope.delete = function(porudzbina) {
        $scope.porudzbine.forEach(function(e, index) {
            if (e.porudzbinaID == $scope.porudzbina.porudzbinaID) {
                $scope.porudzbina.$delete({id: $scope.porudzbina.porudzbinaID}, function() {
                    $scope.porudzbine.splice(index, 1);
                });
            }
        });
    };

});